let baseUrl = ""
const statusWhiteList = [200]

if (process.env.NODE_ENV === 'development') {
	console.log('开发环境')
	baseUrl = "https://xcx.loconor.com"
	// baseUrl = "https://dev.xcx.loconor.com"
} else {
	console.log('生产环境')
	baseUrl = "https://xcx.loconor.com"
}
import {
	refreshTokenAPI
} from '@/api/user.js'
/**
 * 网络请求
 * 
 * @param {Object} options 配置项
 * @param {String} options.url 请求地址
 * @param {String} [options.method="GET"] 请求地址
 * @param {Object} options.data 数据
 * @param {String} [options.dataType="json"] 如果设为 json，会对返回的数据进行一次 JSON.parse，非 json 不会进行 JSON.parse
 * @param {String} [options.responseType="text"] 设置响应的数据类型。合法值：text、arraybuffer	
 * @param {Object} [options.header={'content-type': "application/json"}] 请求头
 * @param {Number} [options.timeout=6000] 超时时间
 * @param {Boolean}	[options.loading=false] 是否开启loading
 * @param {String} [options.loadingTitle="加载中"] loading文案
 * ...args 其它配置参考 https://uniapp.dcloud.net.cn/api/request/request.html
 */
// 不需要登录的接口
const noToken = [
	'/applets/login/register',
	'/applets/common/getSmsCode',
	'/applets/login/login',
	'/applets/login/changePwd',
	'/applets/common/getBanner',
	'/applets/common/getConfig',
	'/applets/activity/activity/getActivityList',
	'/applets/common/refreshToken',
	"/applets/common/getCityId",
	"/applets/home/getHomeTaskList",
	"/applets/home/getHomeActivityList",
	"/applets/common/getMapData",
	"/applets/task/task/getTaskDetail",
	"/applets/task/comment/getTaskComment",
	"/applets/activity/activity/getActivityDetail",
	"/applets/activity/activity/getApplyActivityList",
	"/applets/activity/comment/getActivityComment",
	"/applets/task/task/getTaskList"
];
const request = (options = {}) => {
	let {
		url,
		method,
		data,
		dataType,
		responseType,
		timeout,
		loading,
		loadingTitle,
		...args
	} = options;
	console.log(66,url);
	let header = {
		'content-type': "application/json"
	}
	// 判断是否需要登录
	if (!(noToken.indexOf(url) >= 0)) {
		
		var expiredTimes = uni.getStorageSync('expireTime');
		var now = Math.round(new Date().getTime() / 1000);
		// 失效时间减去现在时间小于0失效，刷新token
		console.log(expiredTimes - now,'剩余失效时间')
		// if(!expiredTimes){
		// 	uni.reLaunch({
		// 		url: '/pages/login/index'
		// 	})
		// 	return false;
		// }
		if (expiredTimes - now < 0&&uni.getStorageSync("token")) {
		
			// 请求刷新token接口
			refreshTokenAPI().then(res => {
				if (res.code == 200) {
					uni.setStorageSync('token', res.data.token)
					uni.setStorageSync('expireTime', res.data.expire_time) //token过期时间
				} else {
					uni.redirectTo({
						url: '/pages/login/index'
					})
				}
			})
		}else {
		
			// 获取用户 token
			let userToken = uni.getStorageSync('token');
			if (!userToken) {
				uni.reLaunch({
					url: '/pages/login/index'
				})
				return false;
			} else {
				// 将 token 放入请求头中
				header['Token'] = userToken
			}
		}
	}
	return new Promise((resolve, reject) => {
		if (loading) {
			uni.showLoading({
				title: loadingTitle || '加载中',
			})
		}
		uni.request({
			url: (baseUrl + '/api' || '') + (url || ''),
			method: method?.toUpperCase() || "GET",
			data: data || null,
			dataType: dataType || "json",
			responseType: responseType || "text",
			header,
			timeout: timeout || 6000,
			...args,
			success: (res) => {
				if (res.data.code !== 200) {
					if (!statusWhiteList.includes(res.data.code)) {
						if(url!='/applets/user/contact/getPayUserContact'){
							uni.showToast({
								title: res.data.message,
								icon: 'none',
								duration: 2000,
							})
						}
					}
					if (res.data.code == 500) {
						uni.showToast({
							title: res.data.msg,
							icon: 'none',
							duration: 2000,
						})
					}
				
					if (res.data.code == 403) {
						// let userToken = uni.getStorageSync('token');
						// if (userToken) {
						// 	refreshTokenAPI().then(res => {
						// 		if (res.code == 200) {
						// 			uni.setStorageSync('token', res.data.token)
						// 		} else {
						// 				console.log(444444);
						// 			uni.redirectTo({
						// 				url: '/pages/login/index'
						// 			})
						// 		}
						// 	})
						// }
						
					}
				}
				resolve(res.data)
			},
			fail: (error) => {
				uni.showToast({
					title: "网络开小差了",
					icon: 'none',
					duration: 2000,
				})
				reject(error);
			},
			complete() {
				if (loading) {
					uni.hideLoading()
				}
			}
		});
	})

}

/**
 * @param {Object} url
 * @param {Object} data
 * @param {Object} options
 * @param {String} [options.dataType="json"] 如果设为 json，会对返回的数据进行一次 JSON.parse，非 json 不会进行 JSON.parse
 * @param {String} [options.responseType="text"] 设置响应的数据类型。合法值：text、arraybuffer	
 * @param {Object} [options.header={'content-type': "application/json"}] 请求头
 * @param {Number} [options.timeout=6000] 超时时间
 * @param {Boolean}	[options.loading=false] 是否开启loading
 * @param {String} [options.loadingTitle="加载中"] loading文案
 */
const get = function(url, data, options = {}) {
	return request({
		url,
		method: "GET",
		data,
		...options
	})
}

const post = function(url, data, options = {}) {
	return request({
		url,
		method: "POST",
		data,
		...options
	})
}

const put = function(url, data, options = {}) {
	return request({
		url,
		method: "PUT",
		data,
		...options
	})
}

const del = function(url, data, options = {}) {
	return request({
		url,
		method: "DELETE",
		data,
		...options
	})
}
// 头像上传
const headportraits = function() {
	return new Promise((resolve, reject) => {
		uni.chooseImage({
			count: 1,
			success: (res) => {
				uni.uploadFile({
					url: baseUrl + '/api/applets/common/uploadFile',
					filePath: res.tempFilePaths[0],
					header: {
						Token: uni.getStorageSync('token')
					},
					name: 'iFile',
					success: res => {
						const imgRes = JSON.parse(res.data).data.url
						resolve(imgRes)
					},
					fail: () => {
						reject('网络错误');
					}
				});
			}
		})
	})
}
request.get = get
request.post = post
request.put = put
request.delete = del
request.headportraits = headportraits
export default request